package com.ylr.base.framework.interceptor;

import com.ylr.base.common.constant.Constant;
import com.ylr.base.common.enums.ResultEnum;
import com.ylr.base.common.interfaces.BaseResultEnum;
import com.ylr.base.common.po.user.UserPo;
import com.ylr.base.common.tool.Result;
import com.ylr.base.common.utils.UserUtils;
import com.ylr.user.framework.feign.client.YuUserClient;
import com.alibaba.fastjson2.JSON;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2023-04-21 18:10:14
 * className: UserInterceptor 用户鉴权拦截器
 * version: 1.0
 * description:
 */
@AllArgsConstructor
public class AuthInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(AuthInterceptor.class);

    private YuUserClient yuUserClient;

    /**
     * 1、前置拦截
     * @param request  http请求对象
     * @param response http请求结果对象
     * @param handler  目标接口对象
     * @return 校验结果[true-通过 false-拒绝]
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            log.warn("AuthInterceptor 非请求接口操作，直接放行。requestUri={}", request.getRequestURI());
            return true;
        }
        String source = request.getHeader(Constant.SOURCE);
        String module = request.getHeader(Constant.MODULE);
        String channel = request.getHeader(Constant.CHANNEL);
        String authResult = request.getHeader(Constant.AUTH_RESULT);
        String _userId = request.getHeader(Constant.USER_ID);
        String _userPo = request.getHeader(UserPo.class.getSimpleName());

        log.debug("上游服务传递参数。authResult={} source={} module={} channel={} userId={} userPo={}", authResult, source, module, channel, _userId, _userPo);
        if (Constant.AUTH_PASS.equals(authResult)) {
            // 已经认证过
            if (StringUtils.isEmpty(_userPo)) {
                // 设置请求用户
                UserUtils.setUser(_userPo);
            }
            return true;
        }
        if (StringUtils.isEmpty(_userId)) {
            // 传递的用户主键为空，直接返回错误
            writeResponse(request, response, ResultEnum.NO_AUTH);
            return false;
        }

        // 用户权限校验
        Result<UserPo> result = yuUserClient.auth(_userId, module, channel, request.getRequestURI());
        if (result.isSuccess()) {
            // 校验通过
            // 设置请求用户
            UserUtils.setUser(result.getData());
            return true;
        }
        // 传递的用户主键为空，直接返回错误
        writeResponse(request, response, result);
        return false;
    }

    /**
     * 3、最终拦截
     * @param request  http请求对象
     * @param response http请求结果对象
     * @param handler  目标接口对象
     * @param ex       异常对象
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清理请求用户
        UserUtils.deleteUser();
    }

    /**
     * 设置http请求返回结果
     */
    private void writeResponse(HttpServletRequest request, HttpServletResponse response, BaseResultEnum baseResultEnum) {
        try {
            // 重置response
            response.reset();
            response.setStatus(HttpStatus.OK.value());
            // 设置结果类型
            response.setContentType("application/json;charset=utf-8");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            // 设置编码类型
            response.setCharacterEncoding("utf-8");
            Result<Object> result = Result.getResult(baseResultEnum);
            response.getWriter().println(JSON.toJSONString(result));
        } catch (IOException e) {
            log.error("请求结果输出异常。message={}", e.getMessage(), e);
        }
    }

    /**
     * 设置http请求返回结果
     */
    private void writeResponse(HttpServletRequest request, HttpServletResponse response, Result<UserPo> result) {
        try {
            // 重置response
            response.reset();
            response.setStatus(HttpStatus.OK.value());
            // 设置结果类型
            response.setContentType("application/json;charset=utf-8");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            // 设置编码类型
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(JSON.toJSONString(result));
        } catch (IOException e) {
            log.error("请求结果输出异常。message={}", e.getMessage(), e);
        }
    }
}